
//注册页面跳转自动登录
; (function autoUsername(params) {
    const getUsername = localStorage.getItem('loginUsername')
    if (getUsername) {
        document.querySelector('[name="username"]').value = getUsername
    }
})()

//登录逻辑
document.querySelector('#btn-login').addEventListener('click', async e => {
    //获取表单
    const form = document.querySelector('.login-form')
    const data = serialize(form, { hash: true, empty: true })
    const { username, password } = data



    if (username === '' || password === '') {
        showToast('用户名或密码不能为空!')
        return
    }

    if (username.length < 8 || username.length > 30 || password.length < 6 || password.length > 30) {
        showToast('用户名长度要求8-30个字符 密码长度要求6-30个字符')
        return
    }

    try {
        const res = await axios.post('/login', data)
        showToast(res.message)
        // 数据缓存 
        const token = res.data.token
        const username = res.data.username

        localStorage.setItem('token', token)
        localStorage.setItem('username', username)
        //1.5秒后跳转页面
        setTimeout(e => {
            location.href = './index.html'
        }, 1500)
    } catch (error) {
        showToast(error.response.data.message)
    }

})